package com.lxl.securitypermission.controller;

import cn.hutool.core.lang.Assert;
import com.lxl.securitypermission.constant.HttpCode;
import com.lxl.securitypermission.dto.ResponseResult;
import com.lxl.securitypermission.dto.ResponseResultPage;
import com.lxl.securitypermission.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 绫小路
 * @date 2021/1/4 20:39
 * @description
 */
@Api(value = "PermissionController",tags = "PermissionController")
@Controller
@RequestMapping("/admin/permission")
public class PermissionController {

  @Autowired
  private PermissionService permissionService;

  @ApiOperation("授权管理页面")
  @GetMapping("")
  public String index() {
    return "admin/admin-permission";
  }

  @ApiOperation("获取授权列表")
  @GetMapping("list")
  @ResponseBody
  public ResponseResultPage list(Integer page, Integer limit, String search) {
    if ((page != null && (page < 1 || page > 100)) ||
        (limit != null && (limit < 1 || limit > 100))) {
      return new ResponseResultPage(HttpCode.FAIL, "入参page、limit范围分别是：1~100、1~100");
    }
    if (page == null) {
      page = 1;
    }
    if (limit == null) {
      limit = 10;
    }
    return permissionService.getPermissionList(search, page, limit);
  }

  @ApiOperation("关闭某个权限")
  @PostMapping("switch")
  @ResponseBody
  public ResponseResult sw(Integer id, Integer status) {
    Assert.isFalse(id == null, "入参id不能为空！");
    if (status != 1) {
      status = 0;
    }
    return permissionService.sw(id, status);
  }

  @ApiOperation("删除某个权限")
  @PostMapping("delete")
  @ResponseBody
  public ResponseResult delete(Integer id) {
    Assert.isFalse(id == null, "入参id不能为空！");
    return permissionService.delete(id);
  }

  @ApiOperation("编辑权限")
  @PostMapping("edit")
  @ResponseBody
  public ResponseResult edit(Integer id, String pattern, String action) {
    Assert.isFalse(id == null, "入参id不能为空！");
    Assert.notBlank(pattern, "URL不能为空");
    Assert.notBlank(action, "读写权限action不能为空");
    Assert.isFalse(!action.equals("R") && !action.equals("RW"), "读写权限格式错误：R 或 RW");
    return permissionService.edit(id, pattern, action);
  }

  @ApiOperation("添加权限")
  @PostMapping("add")
  @ResponseBody
  public ResponseResult add(String pattern, String action) {
    Assert.notBlank(pattern, "URL不能为空");
    Assert.notBlank(action, "读写权限action不能为空");
    Assert.isFalse(!action.equals("R") && !action.equals("RW"), "读写权限格式错误：R 或 RW");
    return permissionService.add(pattern, action);
  }
}
